<template>
  <div class="app-container">
    <!-- 页面标题和状态筛选 -->
    <div class="page-title">
      <h3>订单管理</h3>
      <div class="status-tabs">
        <el-radio-group v-model="activeStatus" @change="handleStatusChange" size="large">
          <el-radio-button label="">全部({{ getStatusCount('') }})</el-radio-button>
          <el-radio-button
              v-for="status in statusOptions"
              :key="status.code"
              :label="status.code"
          >{{ status.desc }}({{ getStatusCount(status.code) }})
          </el-radio-button>
        </el-radio-group>
      </div>
    </div>
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="订单号" prop="orderNo">
        <el-input
            v-model="queryParams.orderNo"
            placeholder="请输入订单号"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="用户ID" prop="userId">
        <el-input
            v-model="queryParams.userId"
            placeholder="请输入用户ID"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
            type="success"
            plain
            icon="Edit"
            :disabled="single"
            @click="handleUpdate"
            v-hasPermi="['system:order:edit']"
        >修改</el-button>
      </el-col>
      <!-- 修改操作按钮 -->
      <el-col :span="1.5">
        <el-button
            type="danger"
            plain
            icon="Close"
            :disabled="multiple"
            @click="handleCloseOrder"
            v-hasPermi="['system:order:edit']"
        >关闭订单</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="warning"
            plain
            icon="Download"
            @click="handleExport"
            v-hasPermi="['system:order:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="orderList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="订单ID" align="center" prop="orderId" />
      <el-table-column label="订单号" align="center" prop="orderNo" />
      <el-table-column label="订单总金额" align="center" prop="totalAmount">
        <template #default="scope">
          <span>¥{{ scope.row.totalAmount }}</span>
        </template>
      </el-table-column>
      <el-table-column label="实付金额" align="center" prop="payAmount">
        <template #default="scope">
          <span>¥{{ scope.row.payAmount }}</span>
        </template>
      </el-table-column>
      <el-table-column label="订单状态" align="center" prop="status">
        <template #default="scope">
          <el-tag
              :type="getStatusTagType(scope.row.status)"
              effect="light"
          >
            {{ getStatusLabel(scope.row.status) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="支付方式" align="center" prop="payType" >
        <template #default="scope">
          <span>{{ getPayTypeLabel(scope.row.payType)}}</span>
        </template>
      </el-table-column>
      <el-table-column label="支付时间" align="center" prop="payTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.payTime, '{y}-{m}-{d} {h}:{i}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="发货时间" align="center" prop="deliveryTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.deliveryTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="收货时间" align="center" prop="receiveTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.receiveTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['system:order:edit']">修改</el-button>
          <el-button link type="primary" icon="Close" @click="handleCloseOrder(scope.row)" v-hasPermi="['system:order:edit']">关闭订单</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加关闭订单对话框 -->
    <el-dialog title="关闭订单" v-model="closeOrderOpen" width="400px" append-to-body>
      <el-form ref="closeOrderRef" :model="closeOrderForm" label-width="80px">
        <el-form-item label="关闭原因" prop="closeReason">
          <el-input
              v-model="closeOrderForm.closeReason"
              type="textarea"
              :rows="4"
              placeholder="请输入关闭订单的原因"
              maxlength="200"
              show-word-limit
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitCloseOrder">确 定</el-button>
          <el-button @click="closeOrderOpen = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <pagination
        v-show="total>0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
    />

    <!-- 添加或修改订单对话框 -->
    <el-dialog :title="title" v-model="open" width="600px" append-to-body>
      <el-form ref="orderRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="订单号" prop="orderNo">
          <el-input v-model="form.orderNo" placeholder="请输入订单号" :disabled="true" />
        </el-form-item>
        <el-form-item label="订单总金额" prop="totalAmount">
          <el-input v-model="form.totalAmount" placeholder="请输入订单总金额" :disabled="true" />
        </el-form-item>
        <el-form-item label="实付金额" prop="payAmount">
          <el-input v-model="form.payAmount" placeholder="请输入实付金额" :disabled="true" />
        </el-form-item>
        <el-form-item label="支付方式" prop="payType">
          <el-select v-model="form.payType" placeholder="请选择支付方式" :disabled="true">
            <el-option
                v-for="payType in payTypeOptions"
                :key="payType.code"
                :label="payType.desc"
                :value="payType.code"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="订单状态" prop="status">
          <el-select v-model="form.status" placeholder="请选择订单状态" :disabled="true">
            <el-option
                v-for="status in statusOptions"
                :key="status.code"
                :label="status.desc"
                :value="status.code"
            />
          </el-select>
        </el-form-item>

        <!-- 当前地址显示 -->
        <el-form-item label="当前地址">
          <div class="current-address">
            <el-tag v-if="currentAddress.receiverName" type="info">
              {{ currentAddress.receiverName }} {{ currentAddress.receiverPhone }}
            </el-tag>
            <div v-if="currentAddress.province" class="address-detail">
              {{ currentAddress.province }} {{ currentAddress.city }} {{ currentAddress.district }} {{ currentAddress.detailAddress }}
            </div>
            <span v-else class="text-muted">暂无地址信息</span>
          </div>
        </el-form-item>

        <!-- 地址选择 -->
        <el-form-item label="选择新地址" prop="addressId">
          <el-select
              v-model="form.addressId"
              placeholder="请选择收货地址"
              clearable
              filterable
              style="width: 100%"
              @change="handleAddressChange"
          >
            <el-option
                v-for="address in addressOptions"
                :key="address.addressId"
                :label="getAddressLabel(address)"
                :value="address.addressId"
            >
              <div class="address-option">
                <div class="address-main">
                  <span class="receiver">{{ address.receiverName }} {{ address.receiverPhone }}</span>
                  <el-tag v-if="address.isDefault === 1" size="small" type="danger">默认</el-tag>
                </div>
                <div class="address-detail">{{ address.province }} {{ address.city }} {{ address.district }} {{ address.detailAddress }}</div>
              </div>
            </el-option>
          </el-select>
        </el-form-item>

        <!-- 选中的地址预览 -->
        <el-form-item label="选中地址" v-if="selectedAddress">
          <div class="selected-address-preview">
            <div class="preview-content">
              <strong>{{ selectedAddress.receiverName }}</strong>
              <span class="phone">{{ selectedAddress.receiverPhone }}</span>
              <el-tag v-if="selectedAddress.isDefault === 1" size="small" type="danger">默认地址</el-tag>
              <div class="address-text">
                {{ selectedAddress.province }} {{ selectedAddress.city }} {{ selectedAddress.district }} {{ selectedAddress.detailAddress }}
              </div>
            </div>
          </div>
        </el-form-item>

        <el-form-item label="订单备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" :disabled="true" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Order">
import { listOrder, getOrder, updateOrder,getStatusEnums,getPayTypeEnums,getOrderStatusCount,closeOrder,updateOrderAddress } from "@/api/system/order"
import {parseTime} from "@/utils/ruoyi.js";
import { getUserAddressList,getAddressDetail } from "@/api/system/address" // 新增地址查询API

const { proxy } = getCurrentInstance()

const orderList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")
const activeStatus = ref("") // 当前选中的状态
const statusOptions = ref([])
const payTypeOptions = ref([])

const closeOrderOpen = ref(false)
const closeOrderForm = ref({
  orderId: null,
  closeReason:''
})
// 地址相关数据
const addressOptions = ref([]) // 用户地址列表
const currentAddress = ref({}) // 当前订单地址
const selectedAddress = ref(null) // 选中的新地址
// 状态数量统计
const statusCounts = ref({})

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    orderNo: null,
    userId: null,
    minAmount: null,
    maxAmount: null,
    payType: null,
    status: null,
    startTime: null,
    endTime: null,
  },
  rules: {
    addressId: [
      { required: true, message: "请选择收货地址", trigger: "change" }
    ],
  }
})

const { queryParams, form, rules } = toRefs(data)

/** 查询订单列表 */
function getList() {
  loading.value = true
  //过滤空值参数
  const params = {}
  Object.keys(queryParams.value).forEach(key => {
    if (queryParams.value[key] !== null && queryParams.value[key] !== '') {
      params[key] = queryParams.value[key]
    }
  })
  listOrder(params).then(response => {
    orderList.value = response.rows
    total.value = response.total
    loading.value = false

    // 无论是否有筛选条件，都获取对应的统计数量
    getFilteredStatusCount(params)
  })
}

/** 获取筛选后的状态数量统计 */
function getFilteredStatusCount(filterParams) {
const contParams = {}
  Object.keys(filterParams).forEach(key => {
    if (key !== "status" && filterParams[key] !== null && filterParams[key] !== '') {
      countParams[key] = filterParams[key]
    }
  })
  // 移除分页参数，因为统计数量不需要分页
  const { pageNum, pageSize, ...countParams } = filterParams

  getOrderStatusCount(countParams).then(response => {
    statusCounts.value = response.data
  })
}
/** 获取状态枚举和数量统计 */
function getStatusData() {
  // 获取状态枚举
  getStatusEnums().then(response => {
    const statusData = response.data
    statusOptions.value = Object.keys(statusData).map(code => ({
      code: code,
      desc: statusData[code]
    }))
  })
  // 获取状态数量统计
  getOrderStatusCount().then(response => {
    statusCounts.value = response.data
  })
}

/** 根据状态码获取数量 */
function getStatusCount(statusCode) {
  if (statusCode === "") {
    // 计算总数：所有状态数量之和
    let total = 0
    Object.values(statusCounts.value).forEach(count => {
      total += parseInt(count) || 0
    })
    return total
  }
  // 直接使用状态码从返回数据中获取
  return statusCounts.value[statusCode] || 0
}

/** 状态标签变化事件 */
function handleStatusChange(status) {
  activeStatus.value = status
  queryParams.value.pageNum = 1
  //显示对应状态的对应订单
  queryParams.value.status = status === "" ? null : status
  getList()
}
/** 获取状态标签类型（用于 el-tag 的 type 属性） */
function getStatusTagType(status) {
  // 根据状态返回对应的标签类型，例如 'success', 'info', 'warning', 'danger' 等
  const statusMap = {
    '1': 'success', // 例如：1-成功
    '2': 'info',    // 待支付
    '3': 'warning', // 进行中
    '4': 'danger'   // 已取消
    // 根据你的实际状态码配置
  }
  return statusMap[status] || 'info'
}

/** 获取状态显示文本 */
function getStatusLabel(status) {
  // 从 statusOptions 中查找对应的描述
  const statusOption = statusOptions.value.find(option => option.code == status)
  return statusOption ? statusOption.desc : status
}

/** 获取支付方式显示文本 */
function getPayTypeLabel(payType) {
  // 从 payTypeOptions 中查找对应的描述
  const payTypeOption = payTypeOptions.value.find(option => option.code == payType)
  return payTypeOption ? payTypeOption.desc : payType
}
// 取消按钮
function cancel() {
  open.value = false
  reset()
}

/** 获取枚举数据 */
function getEnums() {
  // 获取订单状态枚举
  getStatusEnums().then(response => {
    statusOptions.value = Object.keys(response.data).map(code => ({
      code: code,
      desc: response.data[code]
    }))
  })
// 获取支付方式枚举
  getPayTypeEnums().then(response => {
    payTypeOptions.value = Object.keys(response.data).map(code => ({
      code: code,
      desc: response.data[code]
    }))
  })
}
// 表单重置
function reset() {
  form.value = {
    orderId: null,
    orderNo: null,
    userId: null,
    totalAmount: null,
    payAmount: null,
    freightAmount: null,
    payType: null,
    status: null,
    addressId: null,
    remark: null,
    payTime: null,
    deliveryTime: null,
    receiveTime: null,
    createTime: null,
    updateTime: null
  }
  currentAddress.value = {}
  selectedAddress.value = null
  addressOptions.value = []
  proxy.resetForm("orderRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  queryParams.value = {
    pageNum: 1,
    pageSize: 10,
    orderNo: null,
    userId: null,
    minAmount: null,
    maxAmount: null,
    payType: null,
    status: null,
    startTime: null,
    endTime: null,
  }
  //重置状态标签
  activeStatus.value = ""
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.orderId)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _orderId = row.orderId || ids.value
  getOrder(_orderId).then(response => {
    const orderData = response.data
      form.value = {
      ...orderData
    }
    console.log('订单数据:', orderData)

    // 先设置当前地址信息为订单中的addressId
    currentAddress.value = {
      addressId: orderData.addressId
    }

    // 根据订单的addressId查询对应的详细地址信息
    loadCurrentAddressDetail(orderData.addressId)

    // 加载用户地址列表
    loadUserAddressList(orderData.userId)

    open.value = true
    title.value = "修改订单"
  })
}
/** 根据地址ID加载当前地址的详细信息 */
function loadCurrentAddressDetail(addressId) {
  if (!addressId) {
    console.warn('地址ID为空，无法查询地址详情')
    return
  }

  console.log('开始查询地址详情，地址ID:', addressId)

  // 这里需要调用查询地址详情的API
  // 假设有一个 getAddressDetail 的API方法
  getAddressDetail(addressId).then(response => {
    const addressDetail = response.data
    console.log('地址详情数据:', addressDetail)

    if (addressDetail) {
      // 更新当前地址信息为查询到的详细地址
      currentAddress.value = {
        receiverName: addressDetail.receiverName,
        receiverPhone: addressDetail.receiverPhone,
        province: addressDetail.province,
        city: addressDetail.city,
        district: addressDetail.district,
        detailAddress: addressDetail.detailAddress,
        addressId: addressDetail.addressId,
        isDefault: addressDetail.isDefault
      }
    }
  }).catch(error => {
    console.error('获取地址详情失败:', error)
    // 如果获取地址详情失败，显示地址ID作为提示
    currentAddress.value = {
      addressId: addressId,
      receiverName: '地址信息加载失败',
      detailAddress: `地址ID: ${addressId}`
    }
  })
}
/** 加载用户地址列表 */
function loadUserAddressList(userId) {
  if (!userId) return

  getUserAddressList(userId).then(response => {
    addressOptions.value = response.data || []

    // 设置当前选中的地址
    if (form.value.addressId) {
      const currentAddr = addressOptions.value.find(addr => addr.addressId == form.value.addressId)
      if (currentAddr) {
        selectedAddress.value = currentAddr
      }
    }
  }).catch(error => {
    console.error('获取用户地址列表失败:', error)
    addressOptions.value = []
  })
}

/** 地址选择变化事件 */
function handleAddressChange(addressId) {
  if (addressId) {
    selectedAddress.value = addressOptions.value.find(addr => addr.addressId == addressId)
  } else {
    selectedAddress.value = null
  }
}

/** 获取地址显示标签 */
function getAddressLabel(address) {
  return `${address.receiverName} ${address.receiverPhone} - ${address.province}${address.city}${address.district}${address.detailAddress}`
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["orderRef"].validate(valid => {
    if (valid) {
      // 检查地址是否发生变化
      if (form.value.addressId === currentAddress.value.addressId) {
        proxy.$modal.msgWarning("地址未发生变化")
        return
      }

      // 构建提交数据
      const submitData = {
        orderId: form.value.orderId,
        newAddressId: form.value.addressId
      }

      updateOrderAddress(submitData).then(response => {
        proxy.$modal.msgSuccess("地址修改成功")
        open.value = false
        getList()
      }).catch(error => {
        proxy.$modal.msgError("修改失败：" + (error.message || "未知错误"))
      })
    }
  })
}

/** 关闭订单按钮操作 */
function handleCloseOrder(row) {
  const _orderIds = row.orderId || ids.value
  if (!_orderIds){
    proxy.$modal.msgError("请选择要关闭的订单")
    return
  }
  //如果是批量操作，检查是否选择了订单
  if (Array.isArray(_orderIds)&& _orderIds.length === 0){
    proxy.$modal.msgError("请选择要关闭的订单")
    return;
  }
  //设置要关闭订单的ID
  closeOrderForm.value.orderId =  Array.isArray(_orderIds) ? _orderIds[0] : _orderIds
  closeOrderForm.value.closeReason = ''
  closeOrderOpen.value = true
}
/** 关闭订单提交按钮 */
function submitCloseOrder() {
  proxy.$refs["closeOrderRef"].validate(valid => {
    if (valid) {
      if (!closeOrderForm.value.orderId){
        proxy.$modal.msgError("订单ID不能为空")
        return
      }
      const closeData = {
        orderId: closeOrderForm.value.orderId,
        closeReason: closeOrderForm.value.closeReason
      }
      closeOrder(closeData).then(response => {
        proxy.$modal.msgSuccess("订单关闭成功")
        closeOrderOpen.value = false
        getList()
        //重新获取状态数量统计
        getStatusData()
      }).catch( error=>{
        proxy.$modal.msgError(error.message || "订单关闭失败")
      })
    }
  })
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('system/order/export', {
    ...queryParams.value
  }, `order_${new Date().getTime()}.xlsx`)
}

//初始化
onMounted(() => {
  getList()
  getEnums()
  getStatusData()
})
</script>
<style scoped>
.selected-value {
  margin-top: 8px;
  padding: 4px 8px;
  background: #f0f9ff;
  border: 1px solid #91d5ff;
  border-radius: 4px;
  color: #1890ff;
  font-size: 12px;
}
</style>